package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Client;
import net.ib.mntalk.protocol.Client.DeliverMessagesReq;
import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.Message;
import net.ib.mntalk.protocol.File.ImageOption;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.NetResultReceiver.Receiver;
import net.ib.mtalk.network.TcpClient;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.NotifyingAsyncQueryHandler;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

/**
 * COMMENT : subscribe할 때 DeliverMessages API에 setting되는 callback class<br>
 *    AsyncNetTask 클래스를 상속받지 않는 Task<br>
 *    DeliverMessage는 요청 후 받는 Client API이므로 <br> 
 *    NetResultReceiver에 사용될 Receiver다<br>
 *    서버에서 DeliverMessage API가 호출되면 callback이 onNetResult()함수로 들어온다.
 *    onNetResult()는 서버에서 잘 받았다는 ACK를 보내고 받은 메시지를 Database에 저장하고 끝난다.
 *    
 */
public class DeliverMessagesTask implements Receiver, NotifyingAsyncQueryHandler.AsyncQueryListener {
	
	private Context mContext;
	private NotifyingAsyncQueryHandler mDbHandler;
	private Handler mUiHandler;
	
	public DeliverMessagesTask(Context _context, Handler handler) {
		mContext = _context;
		mDbHandler = new NotifyingAsyncQueryHandler(mContext.getContentResolver(), this);
		mUiHandler = handler;
	}
	
	@Override
	public void onNetResult(int resultCode, Object request, Object result) {
		// 받은 메시지를 처리해야 한다. DeliverMessagesRes를 보내줘야 한다.

		TcpEnvelope received = (TcpEnvelope) result;

		Client.DeliverMessagesReq deliverMessagesReq = (Client.DeliverMessagesReq)received.getMessage();

		Client.DeliverMessagesRes deliverMessagesRes = new Client.DeliverMessagesRes();
		deliverMessagesRes.setResponseCode(Common.SUCCESS);

		TcpEnvelope response = new TcpEnvelope.Builder()
			.setRequestId(received.getRequestId())
			.setType(TcpEnvelope.RESPONSE)
			.setMethodId(received.getMethodId())
			.setMessage(deliverMessagesRes)
			.build();

		// Response!
		TcpClient.send(response);
		
		doAfterGetResult(deliverMessagesReq);
	}

	@Override
	public void onNetError(int resultCode, Object sentObject) {
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
	}

	@Override
	public void onDeleteComplete(int token, Object cookie, int result) {
	}

	@Override
	public void onInsertComplete(int token, Object cookie, Uri uri) {
	}

	@Override
	public void onUpdateComplete(int token, Object cookie, int result) {
	}
	
	protected void doAfterGetResult(DeliverMessagesReq deliverMessagesReq) {
		MTalkLogWriter.d("DeliverMessagesTask.doAfterGetResult()");
		if(!deliverMessagesReq.hasMessage()){
			return;
		}
		Message message = deliverMessagesReq.getMessage();
		if(!message.hasViewUuid() && !message.hasType()){
			return;
		}
		
		ChatDatabaseHelper.syncGetMessages(mContext, message);

		if(message.getUserMassage().getContentType() == Common.CONTENT_TYPE_HTML){
			try{
				ImageOption imageOption = new ImageOption();
				imageOption.setHeight(40);
				imageOption.setWidth(40);
//				Toast.makeText(mContext, "ThumbnailDownload", Toast.LENGTH_SHORT).show();
				ThumbnailDownloadTask task = new ThumbnailDownloadTask(mContext, mUiHandler, 
						InboxDatabaseHelper.getClientUUID(mContext, message.getViewUuid()),
						ChatDatabaseHelper.getClientMessageUuid(mContext, message.getMsgUuid()),
						message.getUserMassage().getAttachFile(), imageOption);
				Log.e("ATOM", "attachfile : " + message.getUserMassage().getAttachFile().toString());
				task.execute();
			} catch (Exception e) {
				MTalkLogWriter.e(e);
			}
		}
		
	}
}
